import React from 'react';
import Taro from '@tarojs/taro';
import { connect } from 'react-redux';
import { View, Image } from '@tarojs/components';
import { AtModal, AtModalContent } from 'taro-ui';

import * as T from '../../types';
import actions from '../../actions/index';
import { store2Props } from '../../selectors';
import { OSS_PATH_PREFIX, OSS_BASE_PATH_PREFIX, IMAGE_EMPTY } from '../../constant';

import dayjs from "dayjs";
dayjs.extend(require('dayjs/plugin/duration'));
type IInfoProps = T.IProps & T.IInfoProps;

import './NextItemModal.less';
import 'taro-ui/dist/style/components/modal.scss';
import 'taro-ui/dist/style/components/flex.scss';

// @ts-ignore
@connect<Partial<IInfoProps>, T.IInfoState>(store2Props, actions)
/**
 * 下期预告模态框
 */
export default class NextItemModal extends React.Component<Partial<IInfoProps>, T.IInfoState> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      atModal: {
        closeOnClickOverlay: false,
      },
      pics: {
        nextModalClose: OSS_PATH_PREFIX + '/nextModalClose.png',
        emptyIcon: OSS_BASE_PATH_PREFIX + '/emptyGrey.png',
      },
      empty: {
        text: ''
      },
      timer: null,
      advanceStartTime: "",
      imageError: {}
    };
  }

  componentWillReceiveProps(nextProps: Readonly<Partial<IInfoProps>>, nextContext: any): void {

    // 打开模态框
    if (nextProps.visible == true && this.props.visible == false) {
      if (nextProps.main.nextItem.items.length > 0) {
        this.handleTimerCountdown() // 倒计时
      }
    }

    // 关闭模态框
    if (nextProps.visible == false && this.props.visible == true) {
      // 清除定时器
      const { timer } = this.state;
      clearInterval(timer)
      this.setState({
        timer: null
      })
    }
  }

  /**
   * 残忍拒绝
   */
  handleCancel = () => {
    this.props.onCancel();
  };

  /**
   * 开通会员
   */
  handleActivate = () => {
    // 开通会员界面跳转
    this.props.onActivate();
  };

  /**
   * 开启倒计时
   */
  handleTimerCountdown = () => {
    const { main: { nextItem: { info: { advanceStartTime } } } } = this.props;
    let { timer } = this.state;
    let _this = this;
    timer = setInterval(() => {
      let resultTime = _this.handleCountDownTemplate(dayjs(advanceStartTime).unix())
      _this.setState({
        advanceStartTime: resultTime
      })
    }, 1000)

    this.setState({
      timer
    })
  }

  /**
   * 倒计时模版
   * @param endTime 
   * @returns 
   */
  handleCountDownTemplate = (endTime) => {
    var diffTime = dayjs.duration(endTime * 1000 - dayjs());
    console.log('nextItemModal handleCountDownTemplate diffTime', diffTime)
    var year = diffTime.years();  //年
    var month = diffTime.months(); //月
    var day = diffTime.days();   //天
    var hours = diffTime.hours();  //小时
    var minutes = diffTime.minutes(); //分
    var seconds = diffTime.seconds(); //秒
    return `${year}年${month}月${day}天${hours}小时${minutes}分${seconds}秒`;
  }

  /**
   * 渲染
   * @returns
   */
  render() {
    let {
      visible,
      main: {
        nextItem,
      },
      actions: { action },
      navbarSettings
    } = this.props;
    const { atModal } = this.state;
    console.log('nextItemModal render nextItem', nextItem);

    return (
      <AtModal isOpened={visible} className="nextItemModal" closeOnClickOverlay={atModal.closeOnClickOverlay}
      atModalStyle={{top: navbarSettings.navBarHeight}}>
        <AtModalContent>
          <View className="modalContent">
            {this.renderCloseIcon()}
            {nextItem.items.length > 0 ? (
              <>
                {this.renderTime()}
                {this.renderItems()}
              </>
            ) : (
              this.renderEmptyContent()
            )}
          </View>
        </AtModalContent>
      </AtModal>
    );
  }

  /**
   * 渲染关闭按钮
   * @returns
   */
  renderCloseIcon() {
    const {
      pics: { nextModalClose },
    } = this.state;
    return (
      <View className="nextModalClose" onClick={this.handleCloseModal}>
        <Image src={nextModalClose} className="nextModalCloseIcon" />
      </View>
    );
  }

  /**
   * 渲染空
   */
  renderEmptyContent() {
    const {
      pics: { emptyIcon },
      empty: { text },
    } = this.state;

    return (
      <View className="emptyContent">
        <Image src={emptyIcon} className="emptyIcon" />
        <View className="emptyExtraTitle">{text}</View>
      </View>
    );
  }

  /**
   * 关闭模态框
   */
  handleCloseModal = () => {
    this.props.onCancel();
  };

  /**
   * 渲染时间
   * @returns
   */
  renderTime() {
    const {
      main: {
        nextItem: { info },
      },
    } = this.props;
    const { advanceStartTime } = this.state;
    console.log('nextItem renderTime advanceStartTime', advanceStartTime)

    // 处理倒计时渲染
    return <View className="time">{'开启倒计时：' + (advanceStartTime ? advanceStartTime : '')}</View>;
  }

  /**
   * 渲染列表
   * @returns
   */
  renderItems() {
    const {
      main: {
        nextItem: { items },
      },
    } = this.props;
    console.log('nextItemModal renderItems items', items);

    return (
      <View className="at-row nextItems">
        {items.map((i: any, index: number) => (
          <View className="at-col at-col-4 nextItem" key={index}>
            <Image src={i.goodsInfoImg || IMAGE_EMPTY} className="thum" mode="aspectFit"
              onError={(e) =>
                this.handleImageError(e, index, {
                  propName: 'nextItem',
                  extraName: 'items',
                  imageState: 'goodsInfoImg',
                })
              }
            />
            <View className="nextName">{i.goodsInfoName}</View>
            <View className="nextPrice">{'价值￥' + i.price}</View>
          </View>
        ))}
      </View>
    );
  }

  /**
 * 图片加载错误
 * @param e 
 * @param index 
 */
  handleImageError = (e, index, item) => {

    const { main } = this.props;
    const { propName, imageState, extraName } = item;

    let { imageError, pics } = this.state;

    if (imageError[propName + '_' + extraName]) {
      imageError[propName + '_' + extraName] = imageError[propName + '_' + extraName].concat([index]);
    } else {
      imageError[propName + '_' + extraName] = [index];
    }

    let result = JSON.parse(JSON.stringify(main[propName][extraName]));
    let currentImage = imageError[propName + '_' + extraName];
    let ids = currentImage;
    ids.map((i) => {
      result[i] = {
        ...result[i],
        [imageState]: pics.icon,
      };
    });

    this.props.actions.action.commonChange('main.' + propName + '.' + extraName, result);
  }
}
